package com.dagene.weixin.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import sun.misc.BASE64Decoder;

@SuppressWarnings("restriction")
public class FileUtil {

	// base64字符串转化成图片
	public static String GenerateImage(String imgStr, String url) {
		// 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			String filename = UUID.randomUUID().toString();
			// Base64解码
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			// 生成jpeg图片
			String imgFilePath = url + File.separator + filename + ".jpg";// 新生成的图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return filename;
		} catch (Exception e) {
			return null;
		}
	}

	public static HttpURLConnection getDownFile(String mediaid)
			throws Exception {
		HttpURLConnection conn = null;
		try {
			// http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
			String DownFileUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
					+ TokenUtil.getAccessToken() + "&media_id=" + mediaid;
			conn = getObjectByGet(DownFileUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static HttpURLConnection getObjectByGet(String requestUrl)
			throws Exception {
		HttpURLConnection conn = null;
		try {
			URL url = new URL(requestUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("GET");
			conn.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	static Map<String, String> map = null;

	/**
	 * 微信配置文件获取
	 * 
	 * @return
	 */
	public static Map<String, String> getWeiXinProp() {
		try {
			if (map != null) {
				return map;
			}
			map = new HashMap<String, String>();
			Properties prop = new Properties();
			prop.load(FileUtil.class.getResourceAsStream("/weixin.properties"));
			String appid = prop.getProperty("APPID");
			String appsecret = prop.getProperty("APPSECRET");
			String weixinurl = prop.getProperty("WEIXINURL");
			map.put("APPID", appid);
			map.put("APPSECRET", appsecret);
			map.put("WEIXINURL", weixinurl);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

	/*
	 * public static String getFileName(FileItem item) {
	 * 
	 * String fileName = item.getName();
	 * 
	 * fileName = replace(fileName, "\\", "/");
	 * 
	 * // 新命名 fileName = makeFileName(fileName); // 追加扩展名 fileName =
	 * fileName.substring(fileName.lastIndexOf("/") + 1);
	 * 
	 * return fileName; }
	 */

	public static String makeFileName(String filename) {

		// 为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
		// return UUID.randomUUID().toString() + "_" + filename;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");

		String str = sdf.format(new Date());

		return str + "_" + filename;
	}

	public static String getBlob(InputStream in) throws IOException {

		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] data = new byte[4096];
		int count = -1;
		while ((count = in.read(data, 0, 4096)) != -1)
			outStream.write(data, 0, count);

		data = null;
		String result = new String(outStream.toByteArray(), "utf-8");
		return result;

	}
	/*
	 * public static String replace(String source, String oldString, String
	 * newString) {
	 * 
	 * StringBuffer output = new StringBuffer(); int lengthOfSource =
	 * source.length();
	 * 
	 * int lengthOfOld = oldString.length();
	 * 
	 * int posStart = 0;
	 * 
	 * int pos; while ((pos = source.indexOf(oldString, posStart)) >= 0) {
	 * output.append(source.substring(posStart, pos)); output.append(newString);
	 * posStart = pos + lengthOfOld; }
	 * 
	 * if (posStart < lengthOfSource) {
	 * output.append(source.substring(posStart)); }
	 * 
	 * return output.toString(); }
	 */
	/*
	 * public static String getFileEndWitsh(String contentType){
	 * 
	 * String[] ss = contentType.split("/");
	 * 
	 * return "."+ss[1]; }
	 */
}
